#!/usr/bin/env sh

: ${CI=}
: ${PREFER_BUILDCTL=}
: ${PREFER_LEGACY=}
: ${CLI_PLATFORM=}
: ${GITHUB_ACTIONS=}
: ${CACHEDIR_FROM=}
: ${CACHEDIR_TO=}

if [ "$PREFER_BUILDCTL" = "1" ]; then
  echo >&2 "WARNING: PREFER_BUILDCTL is no longer supported. Ignoring."
fi

if [ "$PREFER_LEGACY" = "1" ]; then
  echo >&2 "WARNING: PREFER_LEGACY is no longer supported. Ignoring."
fi

progressFlag=""
if [ "$CI" = "true" ]; then
  progressFlag="--progress=plain"
fi

buildxCmd() {
  if docker buildx version >/dev/null 2>&1; then
    set -x
    docker buildx "$@" $progressFlag
  elif buildx version >/dev/null 2>&1; then
    set -x
    buildx "$@" $progressFlag
  elif docker version >/dev/null 2>&1; then
    set -x
    DOCKER_BUILDKIT=1 docker "$@" $progressFlag
  else
    echo >&2 "ERROR: Please enable DOCKER_BUILDKIT or install standalone buildx"
    exit 1
  fi
}

if [ -z "$CLI_PLATFORM" ]; then
  if [ "$(uname -s)" = "Darwin" ]; then
      arch="$(uname -m)"
      if [ "$arch" = "x86_64" ]; then
          arch="amd64"
      fi
      CLI_PLATFORM="darwin/$arch"
  elif uname -s | grep MINGW > /dev/null 2>&1 ; then
    CLI_PLATFORM="windows/amd64"
  fi
fi

cacheType=""
cacheRefFrom=""
cacheRefTo=""
currentref=""
if [ "$GITHUB_ACTIONS" = "true" ]; then
  currentref="git://github.com/$GITHUB_REPOSITORY#$GITHUB_REF"
  cacheType="local"
  cacheRefFrom="$CACHEDIR_FROM"
  cacheRefTo="$CACHEDIR_TO"
fi

currentcontext="."
if [ -n "$currentref" ]; then
  currentcontext="--build-arg BUILDKIT_CONTEXT_KEEP_GIT_DIR=1 $currentref"
fi
